package com.timedomain.him.remake.core;

import android.content.Context;

import com.timedomain.him.remake.utils.AppSettings;
import com.timedomain.him.remake.utils.FileUtils;

import org.jetbrains.annotations.Nullable;

import java.util.List;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

// 带播放列表
public class ListPlayer extends BasePlayer implements AutoStopable{
    Timer tickTimer = null;

    public static class PlayEntry{
        public String title;
        public String path;

        @Override
        public boolean equals(@Nullable Object obj) {
            if(!(obj instanceof PlayEntry)){return false;}
            PlayEntry cobj = (PlayEntry)obj;
            if(cobj.path == null){return false;}
            return cobj.equals(this.path);
        }

        @Override
        public int hashCode() {
            return Objects.hash(path);
        }

        public PlayEntry(String path){
            this.path = path;
            this.title = FileUtils.getFileNameWithoutExtension(path);
        }
    }

    private List<PlayEntry> playList;
    private Context ctx;
    public ListPlayer(Context ctx,List<PlayEntry> playList,PlayEntry position){
        this.ctx = ctx;
        this.playList = playList;
        this.position = 0;
        for (int i = 0; i < playList.size(); i++) {
            if(playList.get(i).path.equals(position.path)){
                this.position = i;
                break;
            }
        }
        createInternalPlayer();
        this.loopMode = AppSettings.playerLoopMode;
    }

    private void createInternalPlayer(){
        if(internalPlayer != null){
            internalPlayer.close();
            internalPlayer = null;
        }
        internalPlayer = new SimplePlayer(ChannelCreator.FromFile(ctx,playList.get(position).path));
        internalPlayer.setVolume(_volume);
    }

    private PlayEntry getCurrent(){
        return playList.get(position);
    }

    private SimplePlayer internalPlayer = null;

    private int position = 0;

    @Override
    public void start() {
        if(internalPlayer == null){
            createInternalPlayer();
        }
        internalPlayer.start();
        if(tickTimer != null) {
            tickTimer.cancel();
            tickTimer = null;
        }
        tickTimer = new Timer();

        tickTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                onTick();
            }
        },100L,1000L);
    }

    public String getTitle(){
        return getCurrent().title;
    }

    public void prev(){
        if(loopMode == 2){
            position = (int) (Math.random() * playList.size());
            if(position >= playList.size()){
                position = playList.size()-1;
            }
        }
        else{
            position--;
            if(position<0){
                position = playList.size()-1;
            }
        }
        createInternalPlayer();
        start();
    }

    public void next(){
        if(loopMode == 2){
            position = (int) (Math.random() * playList.size());
            if(position >= playList.size()){
                position = playList.size()-1;
            }
        }
        else{
            position++;
            if(position >= playList.size()){
                position = 0;
            }
        }
        createInternalPlayer();
        start();
    }

    // 设置睡眠模式定时器。-1为禁用，-2为当前播放完成后停止。正数为分钟
    public void setSleepTimer(int duration){
        this.sleepTimerMode = duration;
        if(duration > 0){
            this.endTimeInMillis = System.currentTimeMillis() + 60 * 1000 * duration + 59000;
        }
    }

    private long endTimeInMillis = -1;


    public void onTick(){
        if(isStopped()){
            if(sleepTimerMode != -2){
                if(loopMode != 0){
                    next();
                }
                else{
                    createInternalPlayer();
                    start();
                }
            }
            else{
                setSleepTimer(-1);
                stop();
            }
        }
        else{
            if(sleepTimerMode > 0 && getSleepTimer() == 0){
                pause();
                setSleepTimer(-1);
            }
        }
    }

    private int sleepTimerMode = -1;

    public int getSleepTimer(){
        if(sleepTimerMode < 0){return sleepTimerMode;}
        return (int) ((endTimeInMillis - System.currentTimeMillis()) / 60000L);
    }

    // 播放器模式下的循环模式 0-单个循环 1-列表循环 2-随机播放
    private int loopMode = 1;

    public int getLoopMode(){
        return loopMode;
    }

    public void setLoopMode(int loopMode){
        this.loopMode = loopMode;
    }

    @Override
    public float getPeak() {
        return internalPlayer == null ? 0 : internalPlayer.getPeak();
    }

    @Override
    public void stop() {
        if(internalPlayer != null){

            internalPlayer.stop();
        }
        if(tickTimer != null){

            tickTimer.cancel();
        }
        tickTimer = null;
    }

    @Override
    public void pause() {
        internalPlayer.pause();
    }

    @Override
    public void close() {
        if(internalPlayer != null){

            internalPlayer.close();
        }
        if(tickTimer != null){
            tickTimer.cancel();
        }
    }

    @Override
    public boolean isPlaying() {
        return internalPlayer != null && internalPlayer.isPlaying();
    }

    @Override
    public long getDuration() {
        return internalPlayer == null ? 1 : internalPlayer.getDuration();
    }

    @Override
    public long getPosition() {
        return internalPlayer == null ? 0 : internalPlayer.getPosition();
    }

    @Override
    public boolean isStopped() {
        return internalPlayer == null || internalPlayer.isStopped();
    }

    private float _volume = 1.0f;
    @Override
    public void setVolume(float volume) {
        _volume = volume;
        if(internalPlayer != null){
            internalPlayer.setVolume(volume);
        }
    }

    @Override
    public float getVolume() {
        return _volume;
    }

    @Override
    public void setPosition(long pos) {
        if(internalPlayer != null){
            internalPlayer.setPosition(pos);
        }
    }


    boolean lastIsPlaying = true;
    long lastPausedTime = -1;

    @Override
    public boolean shouldStop() {
        boolean nowIsPlaying = isPlaying();
        if(lastIsPlaying == true && nowIsPlaying == false){
            lastPausedTime = System.currentTimeMillis();
        }
        lastIsPlaying = nowIsPlaying;
        if(!nowIsPlaying){
            if(System.currentTimeMillis() - lastPausedTime > 60 * 5 * 1000){
                return true;
            }
        }
        return false;
    }

}
